#ifndef __H_SERVER_M__
#define  __H_SERVER_M__

#include "util.hpp"
#include "db.hpp"
#include "room.hpp"
#include "online.hpp"
#include "session.hpp"
#include "matcher.hpp"

using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;
#define WWWROOT "./wwwroot/"

class gobang_server
{
public:
    gobang_server(const string& host, const string& username, const string& password,
                const string& dbname, uint16_t port = 3306, const string& wb_root = WWWROOT)
        :_wb_root(wb_root), _ut(host, username, password, dbname, port), _rm(&_ut, &_om)
        ,_sm(&_wssvr), _mm(&_ut, &_om, &_rm)
        {
            _wssvr.set_access_channels(websocketpp::log::alevel::none);

            _wssvr.init_asio();
            _wssvr.set_reuse_addr(true);
            // 设置回调函数
            _wssvr.set_http_handler(bind(&gobang_server::http_callback, this, _1));
            _wssvr.set_open_handler(bind(&gobang_server::wsopen_callback, this, _1));
            _wssvr.set_close_handler(bind(&gobang_server::wsclose_callback, this, _1));
            _wssvr.set_message_handler(bind(&gobang_server::wsmessage_callback, this, _1, _2));
        }
    
    void start(int port)
    {
        _wssvr.listen(port);
        _wssvr.start_accept();
        _wssvr.run();
    }
private:
    void file_handler(wsserver_t::connection_ptr& conn)
    {
        websocketpp::http::parser::request req = conn->get_request();
        string uri = req.get_uri();
        string realpath = _wb_root + uri;

        if(realpath.back() == '/')
            { realpath += "login.html"; }
        
        string body;
        bool ret = file_util::read(realpath, body);
        if(ret == false )
        {
            body += "<html><head><meta charset=\"UTF-8\"></head><body><h1>你所访问的资源不存在, 404! </h1></body></html>";

            conn->set_status(websocketpp::http::status_code::not_found);
            conn->set_body(body);
            return;
        }
        conn->set_status(websocketpp::http::status_code::ok);
        conn->set_body(body);

    }
    void http_resp(wsserver_t::connection_ptr& conn, bool result, 
        websocketpp::http::status_code::value code, const string& reason)
    {
        Json::Value json_resp;
        json_resp["result"] = result;
        json_resp["reason"] = reason;
        string body;
        json_util::serialize(json_resp, body);
        conn->set_status(code);
        conn->append_header("Content-Type", "application/json");
        conn->set_body(body);
    }
    // 注册功能处理
    void reg(wsserver_t::connection_ptr& conn)
    {
        string req_body = conn->get_request_body();
        // 反序列化
        Json::Value resp_info;
        if(json_util::unserialize(req_body, resp_info) == false)
        {
            DLOG("反序列化失败！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "请求正文格式错误！");
        }
        // 
        if(resp_info["username"].isNull() || resp_info["password"].isNull())
        {
            DLOG("用户名/密码不完整！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "请输入用户名/密码！");
        }
        if(_ut.insert(resp_info) == false)
        {
            DLOG("新增用户失败！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "该用户名已存在！");
        }

        return http_resp(conn, true, websocketpp::http::status_code::ok , "用户注册成功！");
    }
    void login(wsserver_t::connection_ptr& conn)
    {
        string req_body = conn->get_request_body();
        // 反序列化
        Json::Value resp_info;
        if(json_util::unserialize(req_body, resp_info) == false)
        {
            DLOG("反序列化失败！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "请求正文格式错误！");
        }
        
        if(resp_info["username"].isNull() || resp_info["password"].isNull())
        {
            DLOG("用户名/密码不完整！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "请输入用户名/密码！");
        }

        if(_ut.login(resp_info) == false)
        {
            DLOG("用户登录失败");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "用户名/密码错误！");
        }
        // 登陆成功创建session
        uint64_t uid = resp_info["id"].asUInt64();
        session_ptr sp = _sm.create_session(uid, LOGIN);
        if(sp.get() == nullptr)
        {
            DLOG("会话创建失败！");
            return http_resp(conn, false, websocketpp::http::status_code::internal_server_error, "会话创建失败！");
        }
        _sm.set_session_expire_time(sp->get_ssid(), SESSION_TIME);

        string cookie_ssid = "SSID=" + to_string(sp->get_ssid());
        conn->append_header("Set-Cookie", cookie_ssid);
        return http_resp(conn, true, websocketpp::http::status_code::ok, "用户登陆成功！");
    }
    bool get_cookie_val(const string& cookie_str, const string& key, string& val)
    {
        // cookie: SSID=xxx; path=/;
        // 以;作为分隔符，进行分割，得到单独的cookie信息
        string sep = "; ";
        vector<string> cookie_arr;
        string_util::split(cookie_str, sep, cookie_arr);

        for(auto str: cookie_arr)
        {
            vector<string> tmp_arr;
            string_util::split(str, "=", tmp_arr);
            if(tmp_arr.size() != 2) { continue;  }
            if(tmp_arr[0] == key) 
            { 
                val = tmp_arr[1]; 
                return true;
            }
        }
        return false;
    }
    void info(wsserver_t::connection_ptr& conn)
    {
        // 获取cookie，从cookie中获取ssid
        string cookie_str = conn->get_request_header("Cookie");
            // 没有cookie就返回错误
        if(cookie_str.empty())
        {
           
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "没有找到cookie信息，请重新登录！"); 
        }
        string ssid_str;
        if(get_cookie_val(cookie_str, "SSID", ssid_str) == false)
        {
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "没有找到ssid信息，请重新登录！"); 
        }
        // 查找对应的会话信息
        session_ptr ssp = _sm.get_session_by_ssid(stol(ssid_str));
        if(ssp.get() == nullptr)
        {
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "登录过期，请重新登录！"); 
        }

        // 取出用户信息发送给客户端
       
        Json::Value user_info;
        if(_ut.select_by_id(ssp->get_user(), user_info) == false)
        {
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "找不到用户信息，请重新登录！"); 
        }
        string body;
        json_util::serialize(user_info, body);
        conn->set_status(websocketpp::http::status_code::ok);
        conn->append_header("Content-Type", "application/json");
        conn->set_body(body);
        
        // 刷新session的过期时间
        _sm.set_session_expire_time(ssp->get_ssid(), SESSION_TIME);
    }

    void http_callback(websocketpp::connection_hdl hdl)
    {
        wsserver_t::connection_ptr conn = _wssvr.get_con_from_hdl(hdl);
        websocketpp::http::parser::request req = conn->get_request();

        string method = req.get_method();
        string uri = req.get_uri();
        if(method == "POST" && uri == "/reg")
            { return reg(conn); }
        else if(method == "POST" && uri == "/login")
            { return login(conn); }
        else if(method == "GET" && uri == "/info")
            { return info(conn); }
        else
            { return file_handler(conn); }

    }
    // ----------------------------------------------------------------------

    void ws_resp(wsserver_t::connection_ptr& conn, const string& optype, bool result, const string& reason)
    {
        Json::Value json_resp;
        json_resp["optype"] = optype;
        json_resp["result"] = result;
        json_resp["reason"] = reason;
        string body;
        json_util::serialize(json_resp, body);
        conn->send(body);
    }
    session_ptr get_session_by_cookie(wsserver_t::connection_ptr& conn)
    {
        // 获取cookie，从cookie中获取ssid
        string cookie_str = conn->get_request_header("Cookie");
            // 没有Cookie返回错误
        if(cookie_str.empty())
        {
            ws_resp(conn, "hall_ready", false, "找不到Cookie信息，请重新登录！");
            return session_ptr();
        }

        // 从Cookie中取出ssid
        string ssid_str;
        if(get_cookie_val(cookie_str, "SSID", ssid_str) == false)
        {
            ws_resp(conn, "hall_ready", false, "没有找到ssid信息，请重新登录！");
            return session_ptr();
        }

        // 通过ssid获取对应的会话信息
        session_ptr ssp = _sm.get_session_by_ssid(stol(ssid_str));
        if(ssp.get() == nullptr)
        {
            ws_resp(conn, "hall_ready", false, "登录过期，请重新登录！");
            return session_ptr();
        }
        // 
        return ssp;
    }
    void wsopen_game_hall(wsserver_t::connection_ptr& conn)
    {
        // 判断当前客户端是否登录
        session_ptr ssp = get_session_by_cookie(conn);
        if(ssp.get() == nullptr)
            { return; }

        // 判断当前客户端是否重复登录，不支持被挤下线的功能
        if(_om.is_in_game_hall(ssp->get_user()) || _om.is_in_game_room(ssp->get_user()))
        {
            return ws_resp(conn, "hall_ready", false, "玩家重复登录");
        }
        // 将客户端以及链接加入大厅
        _om.enter_game_hall(ssp->get_user(),conn);
        // 将session设置为永久存在
        _sm.set_session_expire_time(ssp->get_ssid(), SESSION_FOREVER);

        // 给客户端响应，大厅建立成功
        ws_resp(conn, "hall_ready", true, "大厅连接成功");
        
    }
    void wsopen_game_room(wsserver_t::connection_ptr& conn)
    {
        session_ptr ssp = get_session_by_cookie(conn);
        if(ssp.get() == nullptr)
            { return; }

        // 判断当前客户端是否重复登录，不支持被挤下线的功能
        if(_om.is_in_game_hall(ssp->get_user()) || _om.is_in_game_room(ssp->get_user()))
        {
            return ws_resp(conn, "room_ready", false, "玩家重复登录");
        }
        // 判断房间有没有创建
        room_ptr rp = _rm.get_room_by_uid(ssp->get_user());
        if(rp.get() == nullptr)
        {
            return ws_resp(conn, "room_ready", false, "找不到玩家的游戏房间！");
        }
        _om.enter_game_room(ssp->get_user(), conn);

        _sm.set_session_expire_time(ssp->get_ssid(), SESSION_FOREVER);

        Json::Value json_resp;
        json_resp["optype"] = "room_ready";
        json_resp["result"] = true;
        json_resp["reason"] = "房间连接成功";
        json_resp["room_id"] = (Json::UInt64)rp->get_room_id();
        json_resp["uid"] = (Json::UInt64)ssp->get_user();
        json_resp["white_id"] = (Json::UInt64)rp->get_white_id();
        json_resp["black_id"] = (Json::UInt64)rp->get_black_id();
        string body;
        json_util::serialize(json_resp, body);
        conn->send(body);
        
    }
    void wsopen_callback(websocketpp::connection_hdl hdl)
    {
        wsserver_t::connection_ptr conn = _wssvr.get_con_from_hdl(hdl);
        websocketpp::http::parser::request req = conn->get_request();
        string uri = req.get_uri();

        if(uri == "/hall")
        {
            return wsopen_game_hall(conn);
        }
        else if(uri == "/room")
        {
            return wsopen_game_room(conn);
        }
    }
    //--------------------------------------------------------------------------- 
    void wsclose_game_hall(wsserver_t::connection_ptr& conn)
    {
        // 获取客户端的session信息
        session_ptr ssp =  get_session_by_cookie(conn);
        if(ssp.get() == nullptr)
            { return ; }

        // 将玩家从游戏大厅的在线用户管理中移除
        _om.exit_game_hall(ssp->get_user());

        // 将session设置为定时销毁
        _sm.set_session_expire_time(ssp->get_ssid(), SESSION_TIME);
    }
    void wsclose_game_room(wsserver_t::connection_ptr& conn)
    {
        // 获取客户端的session信息
        session_ptr ssp = get_session_by_cookie(conn);
        if(ssp.get() == nullptr)
            { return ; }
        // 将玩家从游戏大厅的在线用户管理中移除
        _om.exit_game_room(ssp->get_user());
        // 将session设置为定时销毁
        _sm.set_session_expire_time(ssp->get_ssid(), SESSION_TIME);
        // 把用户从房间中移除，所有用户一处房间后，房间会自动销毁
        _rm.remove_room_user(ssp->get_user());

    }
    void wsclose_callback(websocketpp::connection_hdl hdl)
    {
        wsserver_t::connection_ptr conn = _wssvr.get_con_from_hdl(hdl);
        websocketpp::http::parser::request req = conn->get_request();
        string uri = req.get_uri();
        if(uri == "/hall")
        {   
            return wsclose_game_hall(conn);
        }
        else if(uri == "/room")
        {
            return wsclose_game_room(conn);
        }
    }
    // --------------------------------------------------------------------------
    void wsmsg_game_hall(wsserver_t::connection_ptr& conn, wsserver_t::message_ptr& msg)
    {
        // 获取客户端的session信息
        session_ptr ssp = get_session_by_cookie(conn);
        if(ssp.get() == nullptr)
            { return; }

        // 获取请求信息
        Json::Value json_resp;
        string req_body = msg->get_payload();
        if(json_util::unserialize(req_body, json_resp) == false)
        {
            return ws_resp(conn, "unknow", false, "请求正文格式错误！");
        }
        // 对请求信息进行处理
            // 开始匹配
        if(!json_resp["optype"].isNull() && json_resp["optype"].asString() == "match_start")
        {
            if(_mm.add(ssp->get_user()) == false)
                { return ws_resp(conn, "match_start", false, "匹配时获取用户信息失败！"); }
            return ws_resp(conn, "match_start", true, "成功加入匹配队列！");
        }
            // 取消匹配
        else if(!json_resp["optype"].isNull() && json_resp["optype"].asString() == "match_stop")
        {
            if(_mm.del(ssp->get_user()) == false)
                { return ws_resp(conn, "match_stop", false, "取消时获取用户信息失败"); }
            return ws_resp(conn, "match_stop", true, "取消匹配成功！");
        }
        // 请求类型为空
        return ws_resp(conn, "unknow", false, "未知请求类型！");
    }
    void wsmsg_game_room(wsserver_t::connection_ptr& conn, wsserver_t::message_ptr& msg)
    {
        session_ptr ssp = get_session_by_cookie(conn);
        if(ssp.get() == nullptr)
            { return; }
        
        Json::Value json_resp;
        string req_body = msg->get_payload();
        if(json_util::unserialize(req_body, json_resp) == false)
        {
            return ws_resp(conn, "unknow", false, "请求正文格式错误");
        }
        // 获取房间信息
        room_ptr rp = _rm.get_room_by_uid(ssp->get_user());
        if(rp.get() == nullptr)
            { return ws_resp(conn, "unknow", false, "获取房间信息失败！"); }
        // 通过房间模块进行处理
        rp->handler_message(json_resp);
    }
    // 
    void wsmessage_callback(websocketpp::connection_hdl hdl, wsserver_t::message_ptr msg)
    {
        wsserver_t::connection_ptr conn = _wssvr.get_con_from_hdl(hdl);
        websocketpp::http::parser::request req = conn->get_request();
        string uri = req.get_uri();
        if(uri == "/hall")
        {
            return wsmsg_game_hall(conn,msg);
        }
        else if(uri == "/room")
        {
            return wsmsg_game_room(conn,msg);
        }
    }

private:
    string _wb_root;    //静态资源根目录
    wsserver_t _wssvr;
    user_table _ut;
    online_manager _om;
    room_manager _rm;
    session_manager _sm;
    matcher _mm;

};


#endif